package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.Result;
import com.itheima.common.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * DemoInterceptor
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/7/18 15:19
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("=============================拦截成功=====================");

        String token = request.getHeader("Token");

        if (!StringUtils.hasText(token)) {
            // 失败了，不放行？
            Result<?> notLogin = Result.error("NOT_LOGIN");
            // 对象变成json串?
            String json = JSON.toJSONString(notLogin);

            // 设置响应头，表示响应的数据类型是JSON
            response.setContentType("application/json;charset=utf-8");
            // 将数据写进响应体中
            response.getWriter().write(json);
            return false;
        }

        try {
            JwtUtils.parseJWT(token);
            return true;
        } catch (Exception e) {
            // 失败了，不放行？
            Result<?> notLogin = Result.error("NOT_LOGIN");
            // 对象变成json串?
            String json = JSON.toJSONString(notLogin);

            response.setContentType("application/json;charset=utf-8");
            // 响应
            response.getWriter().write(json);

        }
        return false;
    }
}
